package com.example.material.service.impl;

import com.alibaba.excel.EasyExcel;
import com.example.material.entity.Material;
import com.example.material.repository.MaterialRepository;
import com.example.material.service.MaterialService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.transaction.Transactional;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 物料服务实现
 */
@Service
@RequiredArgsConstructor
public class MaterialServiceImpl implements MaterialService {
    private final MaterialRepository materialRepository;

    @Override
    public Material create(Material material) {
        if(material.getStock() < 0) throw new RuntimeException("库存数量不能小于0！");
        if(material.getPrice().doubleValue()<=0) throw new RuntimeException("单价不能小于0！");
        return materialRepository.save(material);
    }

    @Override
    public Material update(Long id, Material material) {
        if(material.getStock() < 0) throw new RuntimeException("库存数量不能小于0！");
        if(material.getPrice().doubleValue()<=0) throw new RuntimeException("单价不能小于0！");
        Material old = materialRepository.findById(id).orElseGet(Material::new);
        material.setId(id);
        material.setCreatedAt(old.getCreatedAt());
        return materialRepository.save(material);
    }

    @Override
    public void delete(Long id) {
        materialRepository.deleteById(id);
    }

    @Override
    public Material getById(Long id) {
        return materialRepository.findById(id).orElse(null);
    }

    @Override
    public List<Material> getAll() {
        return materialRepository.findAll();
    }

    /**
     * Excel导入
     */
    @Override
    @Transactional
    public void importFromExcel(MultipartFile file) {
        try {
            List<Material> list = EasyExcel.read(file.getInputStream())
                    .head(Material.class)
                    .sheet()
                    .doReadSync();
            materialRepository.saveAll(list);
        } catch (IOException e) {
            throw new RuntimeException("导入失败", e);
        }
    }

    /**
     * Excel导出
     */
    @Override
    public byte[] exportToExcel() {
        List<Material> list = materialRepository.findAll();
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            EasyExcel.write(out, Material.class).sheet("物料").doWrite(list);
            return out.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("导出失败", e);
        }
    }
}
